//
//  RenderBuffer.cpp
//  STDRenderSDK
//
//  Created by 陈学明 on 2023/3/12.
//

#include "STDSRenderBuffer.hpp"
#include "STDSGLFunctions.hpp"

STDSRenderBuffer::STDSRenderBuffer(int _w, int _h) {
    mSizeW = _w;
    mSizeH = _h;
    glGetIntegerv(GL_FRAMEBUFFER_BINDING, &mPreFboId);
    glGetIntegerv(GL_RENDERBUFFER_BINDING, &mPreRboId);
    glGenFramebuffers(1, &mFboId);
    int status = (int)glCheckFramebufferStatus(GL_FRAMEBUFFER);//在低端机上，这行代码能防止在for循环连续创建FBO时，mFboId还没准备好，导致下一行的glBindFramebuffer会Crash的bug
    if (status != GL_FRAMEBUFFER_COMPLETE) {
        LOG_DEBUG("createFromTexture Fail Could not bind post processing frame buffer. currentStatus %d successStatus %d", status,
                 GL_FRAMEBUFFER_COMPLETE);
    }
    glBindFramebuffer(GL_FRAMEBUFFER, mFboId);
    _createRenderBuffer();
    glBindFramebuffer(GL_FRAMEBUFFER, mPreFboId);
    glBindFramebuffer(GL_RENDERBUFFER, mPreRboId);
}

STDSRenderBuffer::~STDSRenderBuffer() {
    _release();
}

GLuint STDSRenderBuffer::getDepId() {
    return mDepId;
}

GLuint STDSRenderBuffer::getRboId() {
    return mRboId;
}

void STDSRenderBuffer::_createRenderBuffer() {
    glGenRenderbuffers(1, &mDepId);
    STDSGLFunctions::checkGlError("RenderBuffer init");
    if (mDepId > 0) {
        glBindRenderbuffer(GL_RENDERBUFFER, mDepId);
        glRenderbufferStorageMultisample(GL_RENDERBUFFER, 4, GL_DEPTH_COMPONENT16, mSizeW, mSizeH);
        glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, mDepId);
        STDSGLFunctions::checkGlError("_createRenderBuffer m_DepId");
        
    }
    glGenBuffers(1, &mRboId);
    if (mRboId > 0) {
        glBindRenderbuffer(GL_RENDERBUFFER, mRboId);
        glRenderbufferStorageMultisample(GL_RENDERBUFFER, 4, GL_RGBA8, mSizeW, mSizeH);
        glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, mRboId);
        STDSGLFunctions::checkGlError("_createRenderBuffer m_DepId");
    }
    
    glBindRenderbuffer(GL_RENDERBUFFER, 0);
}

void STDSRenderBuffer::_release() {
    if((bool)glIsRenderbuffer(mDepId)) {
        
        glDeleteRenderbuffers(1, &mDepId);
        mDepId = HANDLE_NON;
        STDSGLFunctions::checkGlError("glDeleteRenderbuffers m_DepId");
    }
    if((bool)glIsRenderbuffer(mRboId)) {
        glDeleteRenderbuffers(1, &mRboId);
        mRboId = HANDLE_NON;
        STDSGLFunctions::checkGlError("glDeleteRenderbuffers mRboId");
    }
    if ((bool)glIsFramebuffer(mFboId)) {
        glDeleteFramebuffers(1, &mFboId);
        STDSGLFunctions::checkGlError("glDeleteFramebuffers mFboId");
        mFboId = 0;
    }
}
